package com.example.demo.config;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.stream.Stream;

@Component
public class InitSqlRunner {

    private static final Logger logger = LoggerFactory.getLogger(InitSqlRunner.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostConstruct // 应用启动后自动执行
    public void runInitSql() {
        try {
            // 加载 SQL 文件
            var resource = new ClassPathResource("sql/init.sql");
            String sql = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);

            // 按分号拆分 SQL 语句
            Stream.of(sql.split(";"))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .forEach(s -> {
                        try {
                            // 直接执行 SQL 语句，数据库会处理重复插入
                            jdbcTemplate.execute(s);
                            logger.info("执行成功：\n{}", s);
                        } catch (Exception e) {
                            logger.error("执行失败：\n{}", s, e);
                        }
                    });
        } catch (Exception e) {
            logger.error("初始化 SQL 执行失败！", e);
        }
    }
}
